﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates a region.
    /// </summary>
    public class CreateRegion : CreateAuditable<RegionEntity>, 
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("GLBLZ");
            }
        }

        /// <summary>
        /// Gets or sets the code.
        /// </summary>
        public string Code
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the country identifier.
        /// </summary>
        public int CountryID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public RegionFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            if(String.IsNullOrWhiteSpace(Code))
                return Err.Of<RegionEntity>().NotValid("Code");
            return base.Validate(uow);
        }

        protected override void Construct(IUnitOfWork uow, RegionEntity entity)
        {
            base.Construct(uow, entity);

            entity.Code = Code.TrimToLen(10);
            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
            entity.Country = uow.Execute(new GetCountry
            {
                ThrowsException = true,
                EntityID = CountryID
            }).Result;
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates the region.
    /// </summary>
    public class UpdateRegion : UpdateAuditable<RegionEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("GLBLZ");
            }
        }

        /// <summary>
        /// Gets or sets the code.
        /// </summary>
        public string Code
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the country identifier.
        /// </summary>
        public int CountryID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public RegionFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            if(String.IsNullOrWhiteSpace(Code))
                return Err.Of<RegionEntity>().NotValid("Code");
            return base.Validate(uow);
        }

        protected override void Revise(IUnitOfWork uow, RegionEntity entity)
        {
            base.Revise(uow, entity);

            entity.Code = Code.TrimToLen(10);
            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
            entity.Country = uow.Execute(new GetCountry
            {
                ThrowsException = true,
                EntityID = CountryID
            }).Result;
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the region.
    /// </summary>
    public class DeleteRegion : DeleteEntity<RegionEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("GLBLZ");
            }
        }

        #endregion
    }

    /// <summary>
    /// Gets the region by identifier.
    /// </summary>
    public class GetRegion : GetEntity<RegionEntity>,
        IApiOperation
    {
    }

    /// <summary>
    /// Gets the region by code.
    /// </summary>
    public class GetRegionByCode : QueryEntity<RegionEntity>,
        IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets or sets the region code.
        /// </summary>
        public string Code
        {
            get;
            set;
        }

        #endregion

        #region Options

        protected override bool Cacheable
        {
            get
            {
                return true;
            }
        }

        #endregion

        #region Utilities

        protected override IQueryable<RegionEntity> Build(IUnitOfWork uow, IQueryable<RegionEntity> query)
        {
            string code = StringHelper.EnsureNotNull(Code).TrimToLen(10);
            return base.Build(uow, query).Where(x => x.Code.Equals(code));
        }

        #endregion
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over region collection.
    /// </summary>
    public class SearchRegions : SearchOperation<RegionEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchRegions()
        {
            SortDir = SortDirection.Ascending;
            SortBy = new []
            {
                RegionSortBy.ID
            };
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the country identifier.
        /// </summary>
        public int? CountryID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public RegionFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort by.
        /// </summary>
        public RegionSortBy[] SortBy
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<RegionEntity> Build(IUnitOfWork uow, IQueryable<RegionEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => (int)x.Flags, (int)FlagMask);
            if(CountryID.HasValue)
                query = query.Where(x => x.Country.EntityID == CountryID.Value);
            if(SortBy != null)
            {
                for(int i = 0; i < SortBy.Length; i++)
                {
                    switch(SortBy[i])
                    {
                        case RegionSortBy.Code:
                            query = query.OrderBy(x => x.Code, SortDir, i != 0);
                            break;
                        case RegionSortBy.Name:
                            query = query.OrderBy(x => x.Name, SortDir, i != 0);
                            break;
                        default:
                            query = query.OrderBy(x => x.EntityID, SortDir, i != 0);
                            break;
                    }
                }
            }
            return query;
        }

        #endregion
    }

    /// <summary>
    /// Gets the collection of regions as a dictionary, where 
    /// key - region identifier and value - region code.
    /// </summary>
    public class GetRegionDictionary : SearchOperation<RegionEntity, Int32, String>,
        IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets or sets the country identifier.
        /// </summary>
        public int? CountryID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public RegionFlags FlagMask
        {
            get;
            set;
        }

        #endregion

        #region Options

        protected override bool Cacheable
        {
            get
            {
                return true;
            }
        }

        #endregion

        #region Utilities

        protected override IQueryable<RegionEntity> Build(IUnitOfWork uow, IQueryable<RegionEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => (int)x.Flags, (int)FlagMask);
            if(CountryID.HasValue)
                query = query.Where(x => x.Country.EntityID == CountryID.Value);
            query = query.OrderBy(x => x.Code);
            return query;
        }

        protected override IQueryable<KeyValuePair<Int32, String>> Map(IQueryable<RegionEntity> query)
        {
            return query.Select(x => new KeyValuePair<Int32, String>(x.EntityID, x.Name));
        }

        #endregion
    }

    #endregion
}
